<template>
  <li class="todo-item" :class="deleteStyle">
    <input type="checkbox" :checked="done" @change="handleToggle" />
    <span v-if="!isEditing" @click="isEditing = true">{{ content }}</span>
    <input
      v-else
      v-focus
      type="text"
      :value="content"
      @blur="handleEdit"
      @keyup.enter="handleEdit"
    />
    <button @click="handleDelete">删除</button>
  </li>
</template>

<script setup>
import { ref, computed } from 'vue'

import { useTodosStore } from '@/store/todos'

const { toggleTodo, editTodo, removeTodo } = useTodosStore()

const props = defineProps({
  id: {
    type: Number,
  },
  content: {
    type: String,
  },
  done: {
    type: Boolean,
  },
})

const isEditing = ref(false)
// 根据done的值控制deleteStyle的样式
const deleteStyle = computed(() => {
  return props.done ? 'delete' : ''
})

//使用自定义指令来获取焦点
const vFocus = {
  //el代表指令应用的元素，这里是input元素
  mounted(el) {
    el.focus()
  },
}

const handleToggle = (event) => {
  toggleTodo(props.id, event.target.checked)
}

const handleEdit = (event) => {
  editTodo(props.id, event.target.value)
  isEditing.value = false
}

const handleDelete = () => {
  removeTodo(props.id)
}
</script>

<style scoped>
.todo-item {
  display: flex;
  align-items: center;

  height: 40px;
  padding: 0 40px;

  list-style: none;
  border-bottom: 1px solid #eee;
}

.todo-item:hover {
  background-color: #ddd;
}

.todo-item.delete span {
  text-decoration: line-through;
  color: red;
}

.todo-item span,
.todo-item input[type='text'] {
  flex: 1;
  margin: 0 20px;
}

.todo-item button {
  padding: 0 10px;
  outline: none;
}
</style>
